#include "file_streamer.h"

#include <time.h>
#include <sstream>

void music::file_streamer::append_title(boost::shared_ptr<model::title> title)
{
	ofstream ofs(_file.c_str(), ofstream::app | ofstream::out);
	string title_str = title->get_title();
	int tmp = 0;
	while(string::npos != (tmp = title_str.find_first_of(" ", tmp))) {
		title_str.replace(tmp, 1, "%20");
	}
	ofs << title_str << " " << title->get_filename() << " "  
		<< title->get_duration() << endl;
	ofs.close();
}

list<boost::shared_ptr<model::title> > music::file_streamer::read_file()
{
	ifstream ifs(_file.c_str());
	list<boost::shared_ptr<model::title> > rtrn;
	string line;
	string name;
	string file;
	int dur;
	stringstream stream;
	while(ifs.good()) {
		getline(ifs, line);
		stream.str("");
		stream.clear();
		stream.str(line);
		stream >> name >> file >> dur;

		int tmp = 0;
		while(string::npos != 
		      (tmp = name.find_first_of("%20", tmp))) {
			name.replace(tmp, 3, " ");
		}
		boost::shared_ptr<model::title> ptr(
			new model::title(name, dur));
		ptr->set_filename(file);
		rtrn.push_back(ptr);
		name = file = "";
		dur = 0;
	}
	if(rtrn.size() > 0) {
		rtrn.pop_back(); // delete last line because of \n
	}
	ifs.close();
	return rtrn;
}

list<string> music::file_streamer::list_files()
{
	ifstream ifs("index.txt");
	string line;
	stringstream stream;
	string file;
	list<string> files;
	while(ifs.good()) {
		getline(ifs, line);
		stream.str("");
		stream.clear();
		stream.str(line);
		stream >> file;
		files.push_back(file);
	}
	if(files.size() > 0) {
		files.pop_back(); // delete last line because of \n
	}
	return files;
}

void music::file_streamer::create_file(const string &name)
{
	list<string> files = list_files();
	bool found = false;
	for(list<string>::iterator i = files.begin(); i != files.end(); ++i) {
		if((*i) == name) {
			found = true;
			break;
		}
	}
	if(found) {
		return;
	}

	ofstream ofs("index.txt", ofstream::app | ofstream::out);
	ofs << name << endl;
}

